X

Node.js

How to Create & Verify a Json Web Token

September 10, 2022

/*

Create a Json Web Token


*/

Install the jsonwebtoken package with npm. We're going to create a json web token with the jwt.sign method. This method takes four arguments,

The payload or data object that you want to put in the token,

The secret used to verify the token,

An options object, which takes properties like expiresIn,

A callback function that returns the token if the method is successful, error if not.

For the payload, will put an id & a category. The secret will be Lobster Heaven. Will use expiresIn property & set it for 4 hours for the options object. The expiresIn in property is in milliseconds. Finally, if the method is successful it will return the token, if not it will return an error message.

How to create a json web token.

/*

Verify a Json Web Token


*/

To verify the token we use the jwt.verify method. This verifies the token to make sure it was one of tokens we created on our server with jwt.sign. This method takes three arguments,

The token we want to verify,

The secret that we used when we created the token,

A callback function that returns the payload or data object from the token if successful, if not an error.

For the token we'll use the token variable that we used when we created the first token. The secret will be Lobster Heaven. The secret has to be the same as the token we created. For the callback will return the payload data if successful.

jwt.verify to verify the token we created.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.